import Ember from 'ember';
import EmberUploader from 'ember-uploader';

export default Ember.Component.extend(Ember.Evented, {
  uploading: false,
  percenting: "0%",
  url: "/v1/taskitems",
  change: function(e) {
    var input = e.target;
    if (!Ember.isEmpty(input.files)) {
      var files = input.files;

    var uploadUrl = this.get('url'),
        self = this,
        uploader;

    this.set('uploading', true);

    uploader = EmberUploader.Uploader.create({
      url: uploadUrl
    });

    uploader.on('progress', function(e){
      var c = (Math.round(e.percent * 100) / 100) + "%";
      self.set('percenting', c);
    });

    uploader.on('didUpload', function(data){
      self.sendAction('newItemCreated', data);
    });

    uploader.on('didError', function(jqXHR, textStatus, errorThrown){
      // console.log(jqXHR);
    });

    if (!Ember.isEmpty(files)) {
      uploader.upload(files[0]).then(function(data){
        self.set('uploading', false);
        self.set('uploadResponse', data);
      }, function(err){
        self.set('uploading', false);
        self.set('uploadResponse', err);
      });
    }
    }
  }
});
